'use client';

import { useState, useEffect } from 'react';
import { 
  BookOpen, 
  Plus, 
  BarChart3, 
  CheckCircle2, 
  Users,
  FileText,
  Save,
  Filter
} from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { FadeIn } from '@/components/ui/motion';
import { examService, gradeService } from '@/services/gradeService';
import { useToast } from '@/components/ui/use-toast';
import { Toaster } from 'sonner';

const subjects = ['语文', '数学', '英语', '科学', '历史', '地理', '音乐', '美术', '体育'];

export default function GradesPage() {
  const { toast } = useToast();
  const [activeTab, setActiveTab] = useState('entry');
  const [dialogOpen, setDialogOpen] = useState(false);
  const [selectedExam, setSelectedExam] = useState('');
  const [selectedSubject, setSelectedSubject] = useState('');
  
  // 新建考试表单状态
  const [examName, setExamName] = useState('');
  const [examDate, setExamDate] = useState('');
  const [selectedSubjects, setSelectedSubjects] = useState<string[]>([]);
  
  // 数据状态
  const [exams, setExams] = useState<any[]>([]);
  const [grades, setGrades] = useState<Record<string, string>>({});
  const [studentGrades, setStudentGrades] = useState<any[]>([]);
  const [rankingData, setRankingData] = useState<any[]>([]);

  // 初始化加载考试列表
  useEffect(() => {
    loadExams();
  }, []);

  // 加载考试列表
  const loadExams = async () => {
    try {
      const examList = await examService.getAllExams();
      console.log('获取考试列表响应:', examList);
      setExams(examList);
      
      if (examList.length > 0) {
        setSelectedExam(examList[0].id.toString());
        loadRankingData(examList[0].id);
      }
    } catch (error) {
      console.error('加载考试列表失败:', error);
    }
  };

  // 新建考试
  const handleCreateExam = async () => {
    try {
      const examData = {
        name: examName,
        examDate: examDate,
        subjects: subjects.join(','),
        status: 'PENDING' as const,
      };
      
      const result = await examService.createExam(examData);
      
      setDialogOpen(false);
      loadExams();
      
      // 重置表单
      setExamName('');
      setExamDate('');

      // 显示成功提示
      toast({
        title: "考试创建成功",
        description: `已成功创建考试：${examName}`,
      });
    } catch (error) {
      console.error('创建考试失败:', error);
      toast({
        variant: "destructive",
        title: "创建失败",
        description: "创建考试时发生错误，请重试",
      });
    }
  };

  // 加载成绩数据
  const loadGradeData = async (examId: string, subject: string) => {
    if (!examId || !subject) return;
    
    try {
      console.log('获取成绩请求参数:', { examId, subject });
      const gradeData = await gradeService.getExamSubjectGrades(Number(examId), subject);
      console.log('获取成绩响应:', gradeData);
      setStudentGrades(gradeData);
      
      // 转换成绩数据格式
      const gradeMap: Record<string, string> = {};
      gradeData.forEach(grade => {
        if (grade.score !== null) {
          gradeMap[grade.studentId.toString()] = grade.score.toString();
        }
      });
      setGrades(gradeMap);
    } catch (error) {
      console.error('加载成绩数据失败:', error);
    }
  };

  // 加载排名数据
  const loadRankingData = async (examId: number) => {
    try {
      console.log('获取排名请求参数:', { examId });
      const rankingData = await gradeService.getExamRanking(examId);
      console.log('获取排名响应:', rankingData);
      setRankingData(rankingData);
    } catch (error) {
      console.error('加载排名数据失败:', error);
    }
  };

  // 监听考试和科目选择变化
  useEffect(() => {
    if (selectedExam && selectedSubject) {
      loadGradeData(selectedExam, selectedSubject);
    }
  }, [selectedExam, selectedSubject]);

  // 处理成绩输入
  const handleGradeChange = (studentId: number, value: string) => {
    if (value === '' || /^\d*\.?\d*$/.test(value)) {
      setGrades(prev => ({ ...prev, [`${studentId}`]: value }));
    }
  };

  // 保存成绩
  const handleSaveGrades = async () => {
    try {
      const scores: Record<number, number> = {};
      Object.entries(grades).forEach(([studentId, score]) => {
        if (score) {
          scores[Number(studentId)] = Number(score);
        }
      });

      const result = await gradeService.batchEnterGrades(
        Number(selectedExam),
        selectedSubject,
        scores
      );

      // 重新加载成绩数据
      loadGradeData(selectedExam, selectedSubject);

      // 显示成功提示
      toast({
        title: "成绩保存成功",
        description: `已成功保存${Object.keys(scores).length}条成绩记录`,
      });
    } catch (error) {
      console.error('保存成绩失败:', error);
      toast({
        variant: "destructive",
        title: "保存失败",
        description: "保存成绩时发生错误，请重试",
      });
    }
  };

  return (
    <FadeIn>
      <div className="container mx-auto py-6">
        <div className="flex justify-between items-center mb-6">
          <h1 className="text-2xl font-bold">成绩录入</h1>
          <div className="flex space-x-2">
            <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
              <DialogTrigger asChild>
                <Button className="flex items-center">
                  <Plus className="mr-2 h-4 w-4" />
                  新建考试
                </Button>
              </DialogTrigger>
              <DialogContent className="sm:max-w-[500px]">
                <DialogHeader>
                  <DialogTitle>新建考试</DialogTitle>
                  <DialogDescription>创建新的考试记录</DialogDescription>
                </DialogHeader>
                <div className="grid gap-4 py-4">
                  <div className="grid gap-2">
                    <Label htmlFor="examName">考试名称</Label>
                    <Input 
                      id="examName" 
                      placeholder="例如：期末考试"
                      value={examName}
                      onChange={(e) => setExamName(e.target.value)}
                    />
                  </div>
                  <div className="grid gap-2">
                    <Label htmlFor="examDate">考试日期</Label>
                    <Input 
                      id="examDate" 
                      type="date"
                      value={examDate}
                      onChange={(e) => setExamDate(e.target.value)}
                    />
                  </div>
                </div>
                <DialogFooter>
                  <Button variant="outline" onClick={() => setDialogOpen(false)}>取消</Button>
                  <Button onClick={handleCreateExam}>创建</Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>
        </div>
        
        <div className="mb-6">
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center">
                <BarChart3 className="h-5 w-5 mr-2" />
                成绩录入概览
              </CardTitle>
              <CardDescription>
                选择考试和科目进行成绩录入
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                <div className="bg-blue-50 p-4 rounded-lg">
                  <div className="flex justify-between items-center">
                    <div>
                      <p className="text-sm text-gray-500">考试次数</p>
                      <p className="text-2xl font-bold text-blue-600">{exams.length}</p>
                    </div>
                    <div className="p-2 bg-blue-100 rounded-full">
                      <FileText className="h-6 w-6 text-blue-600" />
                    </div>
                  </div>
                </div>
                
                <div className="bg-green-50 p-4 rounded-lg">
                  <div className="flex justify-between items-center">
                    <div>
                      <p className="text-sm text-gray-500">科目数量</p>
                      <p className="text-2xl font-bold text-green-600">{subjects.length}</p>
                    </div>
                    <div className="p-2 bg-green-100 rounded-full">
                      <BookOpen className="h-6 w-6 text-green-600" />
                    </div>
                  </div>
                </div>
                
                <div className="bg-purple-50 p-4 rounded-lg">
                  <div className="flex justify-between items-center">
                    <div>
                      <p className="text-sm text-gray-500">学生人数</p>
                      <p className="text-2xl font-bold text-purple-600">{studentGrades.length}</p>
                    </div>
                    <div className="p-2 bg-purple-100 rounded-full">
                      <Users className="h-6 w-6 text-purple-600" />
                    </div>
                  </div>
                </div>
              </div>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="exam">选择考试</Label>
                  <Select value={selectedExam} onValueChange={setSelectedExam}>
                    <SelectTrigger className="mt-1">
                      <SelectValue placeholder="选择考试" />
                    </SelectTrigger>
                    <SelectContent>
                      {exams.map(exam => (
                        <SelectItem key={exam.id} value={exam.id.toString()}>
                          {exam.name} ({exam.examDate})
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                
                <div>
                  <Label htmlFor="subject">选择科目</Label>
                  <Select value={selectedSubject} onValueChange={setSelectedSubject}>
                    <SelectTrigger className="mt-1">
                      <SelectValue placeholder="选择科目" />
                    </SelectTrigger>
                    <SelectContent>
                      {subjects.map(subject => (
                        <SelectItem key={subject} value={subject}>
                          {subject}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
        
        <Tabs value={activeTab} onValueChange={setActiveTab} className="mb-6">
          <TabsList className="mb-4">
            <TabsTrigger value="entry">成绩录入</TabsTrigger>
            <TabsTrigger value="history">历史成绩</TabsTrigger>
          </TabsList>
          
          <TabsContent value="entry">
            <Card>
              <CardHeader className="pb-2">
                <div className="flex justify-between items-center">
                  <CardTitle className="text-lg">学生成绩录入</CardTitle>
                  <Button 
                    onClick={handleSaveGrades}
                    disabled={!selectedExam || !selectedSubject}
                    className="flex items-center"
                  >
                    <Save className="mr-2 h-4 w-4" />
                    保存成绩
                  </Button>
                </div>
                <CardDescription>
                  {selectedExam && selectedSubject 
                    ? `正在录入: ${exams.find(e => e.id.toString() === selectedExam)?.name} - ${selectedSubject}` 
                    : '请先选择考试和科目'}
                </CardDescription>
              </CardHeader>
              <CardContent>
                {selectedExam && selectedSubject ? (
                  <div className="overflow-x-auto">
                    <table className="w-full text-sm text-left">
                      <thead className="text-xs text-gray-700 uppercase bg-gray-50">
                        <tr>
                          <th className="px-6 py-3">学号</th>
                          <th className="px-6 py-3">姓名</th>
                          <th className="px-6 py-3">成绩</th>
                          <th className="px-6 py-3">状态</th>
                        </tr>
                      </thead>
                      <tbody>
                        {studentGrades.map((student) => (
                          <tr key={student.studentId} className="bg-white border-b">
                            <td className="px-6 py-4">{student.studentNumber}</td>
                            <td className="px-6 py-4 font-medium">{student.name}</td>
                            <td className="px-6 py-4">
                              <Input
                                type="text"
                                placeholder="输入成绩"
                                className="w-24"
                                value={grades[student.studentId] || ''}
                                onChange={(e) => handleGradeChange(student.studentId, e.target.value)}
                              />
                            </td>
                            <td className="px-6 py-4">
                              {student.hasGrade ? (
                                <Badge variant="default">已录入</Badge>
                              ) : (
                                <Badge variant="secondary">未录入</Badge>
                              )}
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                ) : (
                  <div className="text-center py-8">
                    <p className="text-gray-500">请先选择考试和科目</p>
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>
          
          <TabsContent value="history">
            <Card>
              <CardHeader className="pb-2">
                <div className="flex justify-between items-center">
                  <CardTitle className="text-lg">历史成绩查询</CardTitle>
                  <Select 
                    value={selectedExam} 
                    onValueChange={(value) => {
                      setSelectedExam(value);
                      loadRankingData(Number(value));
                    }}
                  >
                    <SelectTrigger className="w-[180px]">
                      <SelectValue placeholder="选择考试" />
                    </SelectTrigger>
                    <SelectContent>
                      {exams.map(exam => (
                        <SelectItem key={exam.id} value={exam.id.toString()}>
                          {exam.name} ({exam.examDate})
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <CardDescription>
                  查看历史考试成绩记录
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="overflow-x-auto">
                  <table className="w-full text-sm text-left">
                    <thead className="text-xs text-gray-700 uppercase bg-gray-50">
                      <tr>
                        <th className="px-6 py-3">学号</th>
                        <th className="px-6 py-3">姓名</th>
                        {subjects.map(subject => (
                          <th key={subject} className="px-6 py-3">{subject}</th>
                        ))}
                        <th className="px-6 py-3">总分</th>
                        <th className="px-6 py-3">排名</th>
                      </tr>
                    </thead>
                    <tbody>
                      {rankingData.map((student) => (
                        <tr key={student.studentId} className="bg-white border-b">
                          <td className="px-6 py-4">{student.studentNumber}</td>
                          <td className="px-6 py-4 font-medium">{student.name}</td>
                          {subjects.map(subject => (
                            <td key={subject} className="px-6 py-4">
                              {student.subjectScores[subject] || '-'}
                            </td>
                          ))}
                          <td className="px-6 py-4 font-bold">{student.totalScore}</td>
                          <td className="px-6 py-4">{student.ranking}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </div>
      <Toaster />
    </FadeIn>
  );
}
